const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');//配置相关的打包后的dist
const { CleanWebpackPlugin } = require('clean-webpack-plugin');//插件，打包后自动清除dist的相关内容
const MiniCssExtractPlugin = require('mini-css-extract-plugin');//单独处理css

module.exports = {
  mode: 'production',
  entry: {
    index: './src/index.js',
    framework: ['react','react-dom'],//webpack 代码分割
  },
  output: {
    // filename: 'js/bundle.js',
    filename: 'js/[name].[chunkhash:8].bundle.js',
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        use: 'babel-loader',
        exclude: /node_modules/,//处理jsx的loader处理
      },
      {
        test: /\.css$/,//处理css样式的loader处理
        use: [ 
          MiniCssExtractPlugin.loader,//单独处理css，把css单独打包出来的配置
          'css-loader' 
        ]
      },
      {
        test: /\.less$/,//处理less的配置
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          'less-loader'
        ]
      },
      {
        test: /\.(sass|scss)$/,//处理sass的配置
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          'sass-loader'
        ]
      },
    ]
  },
  //相关的代码配置,代码分割，把framawork的单独切分出来
  optimization: {
    splitChunks: {//代码分割的配置
      chunks: 'all',
      minSize: 30000,
      maxSize: 0,
      minChunks: 1,
      cacheGroups: {
        framework: {
          test: "framework",//新生成的framework模块会覆盖被抽离的framework模块
          name: "framework",
          enforce: true
        },
        vendors: {
          priority: -10,
          test: /node_modules/,
          name: "vendor",
          enforce: true,
        },
      }
    }
  },
  //自动生成dist目录的配置
  plugins: [
    new HtmlWebpackPlugin({
      filename: 'indexdist.html',//打包后dist 所在文件的名字
      // 这里有小伙伴可能会疑惑为什么不是 '../public/index.html'
      // 我的理解是无论与要用的template是不是在一个目录，都是从根路径开始查找
      template: 'public/index.html',
      inject: 'body',
      minify: {
        removeComments: true,
        collapseWhitespace: true,
      },
    }),
    new MiniCssExtractPlugin({//单独处理css，把css单独打包出来的配置
      filename: 'css/[name].[hash].css',
      chunkFilename: 'css/[id].[hash].css',
    }),
    new CleanWebpackPlugin()//插件，打包后自动清除dist的相关内容
  ]
}
